package org.compression.services.imp;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import javax.servlet.http.HttpServletResponse;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;
import org.compression.controller.FileController;
import org.compression.controller.SearchController;
import org.compression.mapper.AuthMapper;
import org.compression.mapper.GetNamesMapper;
import org.compression.mapper.InsertBookMapper;
import org.compression.mapper.SearchMapper;
import org.compression.mapper.TxtInsertMapper;
import org.compression.services.FileService;
import org.compression.thread.InsertThread;
import org.compression.util.PdfUtil;
import org.model.MedicalScience;
import org.model.SearchModel;
import org.model.SelectModel;
import org.model.TNewMagazine;
import org.model.business.Magazine;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

@Service
@Transactional
public class FileServiceImp implements FileService{


	
	@Value("${file.pathImage}")
	public String pathImage;
	

	private Logger logger = LoggerFactory.getLogger(FileServiceImp.class);

	 ExecutorService pool = Executors.newFixedThreadPool(20);
	@Autowired
	TxtInsertMapper mTxtInsertMapper;

	@Autowired
	SearchMapper mSearchMapper;
	
	@Autowired
	InsertBookMapper mInsertBookMapper;

	@Value("${file.path}")
	public String filepath;
	
	@Value("${file.pathImage}")
	public String filepathImage;
	
	



	@Override
	public void transformation(SearchModel model) {


	}

	@Override
	public Object findFileName(String str) {
		return null;
	}

	@Override
	public Object filedownd(TNewMagazine mTNewMagazine) {
		return mSearchMapper.getMaginzeById(mTNewMagazine.getId());
	}

	@Override
	public Object writeFilePath(MultipartHttpServletRequest request,MultipartFile file,String id) throws Exception {
	//	logger.info(file.getOriginalFilename());
		if(id.equals("")||id==null) {
			return "0000";
		}
		
		mTxtInsertMapper.updateNewMagazinePath(filepath+file.getOriginalFilename(), id);
		BufferedInputStream in;
		in = new BufferedInputStream(request.getInputStream());
		byte[] b=file.getBytes();
		//logger.info(filepath);
	//	logger.info(filepath+file.getOriginalFilename());
		BufferedOutputStream out=new BufferedOutputStream(new FileOutputStream(filepath+file.getOriginalFilename()));
		out.write(b);
		out.flush();
		out.close();
		
		int total=PdfUtil.getNumberOfPages(filepath+file.getOriginalFilename());
		
	//	System.out.println(total);
		 
		for(int i=1;i<=total;i++) {
			 pool.execute(new InsertThread(new File(filepath+file.getOriginalFilename()),i,i,mSearchMapper,id));
		}
	//	logger.info("结束"+Thread.currentThread().getName()+"  "+System.currentTimeMillis()+"");
		return "0001";
	}

	
	@Override
	public Object uploadCover(MultipartHttpServletRequest request,
			MultipartFile file,String id) throws Exception {
		if(id.equals("")||id==null) {
			return "0000";
		}
		mTxtInsertMapper.updateNewMagazineCoverPath(filepathImage+file.getOriginalFilename(), id);
		BufferedInputStream in;
		in = new BufferedInputStream(request.getInputStream());
		byte[] b=file.getBytes();
		BufferedOutputStream out=new BufferedOutputStream(new FileOutputStream(filepathImage+file.getOriginalFilename()));
		out.write(b);
		out.flush();
		out.close();	
		
		
		
		return "0001";
	}
	
	
	
	
	
	
	
	
	
	
	
	
	

	//读写pdf
	public void pdfUitl(File pdfFile,String filepath) {

		// 是否排序
		boolean sort = false;
		// 输入文本文件名称
		String textFileName = null;
		// 编码方式
		String encoding = "UTF-8";
		// 开始提取页数
		int startPage = 1;
		// 结束提取页数
		int endPage = 2;
		// 文件输入流，生成文本文件
		Writer output = null;
		// 内存中存储的PDF Document
		PDDocument document = null;

		File outputFile = null;
		
		try {

			// 从本地装载文件
			//注意参数已不是以前版本中的URL.而是File。
			System.out.println("开始装载文件"+pdfFile.getName());
			document = PDDocument.load(pdfFile);
			if (pdfFile.getName().length() > 4) {
				textFileName = pdfFile.getName().substring(0, pdfFile.getName().length() - 4) + ".txt";
				outputFile = new File(pdfFile.getParent(),textFileName);
				System.out.println("新文件绝对路径为："+outputFile.getAbsolutePath());
			}


			System.out.println("装载文件结束");


			System.out.println("开始写到txt文件中");
			// 文件输入流，写入文件倒textFile
			output = new OutputStreamWriter(new FileOutputStream(outputFile),encoding);
			System.out.println("写入txt文件结束");
			// PDFTextStripper来提取文本
			PDFTextStripper stripper = null;
			stripper = new PDFTextStripper();
			// 设置是否排序
			stripper.setSortByPosition(sort);
			// 设置起始页
			stripper.setStartPage(startPage);
			// 设置结束页
			stripper.setEndPage(endPage);
			// 调用PDFTextStripper的writeText提取并输出文本
			System.out.println("开始调用writeText方法");
			stripper.writeText(document, output);

		}catch (Exception e) {
			// TODO: handle exception
		}
	}

	@Autowired
	AuthMapper 	mAuthMapper;
	//文件下载
	@Override
	public void filedowndImage(HttpServletResponse response,String memberId, String magazineId) throws IOException {
		Magazine path=mAuthMapper.getAuth(memberId, magazineId);
			File imageFile = new File(pathImage+path.getCoverpath());
			logger.info(imageFile.length()+"");
			if (!imageFile.exists()) {
				response.setContentType("text/html; charset=utf8");
				response.getWriter().println("无权限");
				return;
			}
			response.setHeader("content-type", "application/octet-stream");
			response.setContentType("application/octet-stream");
			response.setHeader("Content-Disposition", "attachment;filename="+ new String(imageFile.getName().getBytes("UTF-8"),"iso-8859-1")+"");
		    byte[] buff = new byte[(int) (imageFile.length())];
		    BufferedInputStream bis = null;
		    OutputStream os = null;
		    try {
		        os = response.getOutputStream();
		        bis = new BufferedInputStream(new FileInputStream(imageFile));
		        int i = bis.read(buff);
		        while (i != -1) {
		            os.write(buff, 0, buff.length);
		            os.flush();
		            i = bis.read(buff);
		        }
		    } catch (IOException e) {
		        e.printStackTrace();
		    } finally {
		        if (bis != null) {
		            try {
		                bis.close();
		            } catch (IOException e) {
		                e.printStackTrace();
		            }
		        }
		    }   
	}

	@Override
	public void filedowndpdf(HttpServletResponse response, String memberId, String magazineId) throws IOException {
		Magazine path=mAuthMapper.getAuth(memberId, magazineId);
		File pdfFile = new File(filepath+path.getPath());
		logger.info(pdfFile.getName()+"");
		if (!pdfFile.exists()) {
			response.setContentType("text/html; charset=utf8");
			response.getWriter().println("无权限");
			return;
		}
		response.setHeader("content-type", "application/octet-stream");
		response.setContentType("application/octet-stream");
		response.setCharacterEncoding("UTF-8");
		response.setHeader("Content-Disposition", "attachment;filename="+ new String(pdfFile.getName().getBytes("UTF-8"),"iso-8859-1")+"");
	    byte[] buff = new byte[(int) (pdfFile.length())];
	    BufferedInputStream bis = null;
	    OutputStream os = null;
	    try {
	        os = response.getOutputStream();
	        bis = new BufferedInputStream(new FileInputStream(pdfFile));
	        int i = bis.read(buff);
	        while (i != -1) {
	            os.write(buff, 0, buff.length);
	            os.flush();
	            i = bis.read(buff);
	        }
	    } catch (IOException e) {
	        e.printStackTrace();
	    } finally {
	        if (bis != null) {
	            try {
	                bis.close();
	            } catch (IOException e) {
	                e.printStackTrace();
	            }
	        }
	    }   
	}

	
	
	
	
	public  void uitlDown(HttpServletResponse response, String memberId, String magazineId) throws IOException {
		
	
	}
	
	
	
	
	
	
	
	
	
	
	
	
	
	

}
